//
//  URL+Commpent.swift
//  NyamanDana
//
//  Created by 李永彬 on 2025/11/14.
//

import Foundation

extension URL {
    static func buildURL(with urlString: String) -> URL? {
        guard var urlComponents = URLComponents(string: urlString) else {
            return nil
        }
        
        let commonParams = NDNetworkService.shared.requestBuilder.commonParameters
        let commonQueryString = commonParams.urlQueryString
        
        guard !commonQueryString.isEmpty else {
            return urlComponents.url
        }
        
        // 解析公共参数字符串为 URLQueryItem 数组
        let commonQueryItems = commonQueryString.components(separatedBy: "&").compactMap { pair -> URLQueryItem? in
            let components = pair.components(separatedBy: "=")
            guard components.count == 2 else { return nil }
            return URLQueryItem(name: components[0], value: components[1])
        }
        
        // 合并查询参数
        var existingQueryItems = urlComponents.queryItems ?? []
        existingQueryItems.append(contentsOf: commonQueryItems)
        urlComponents.queryItems = existingQueryItems
        
        return urlComponents.url
    }
}
